<template>
  <div class="contacts-container">
    <!-- 头部工具栏 -->
    <div class="contacts-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon><User /></el-icon>
          {{ $t('contacts.title') }}
        </h2>
        <div class="stats-info">
          <span class="stat-item">
            {{ $t('contacts.stats.friends') }} {{ contactsStore.totalFriends }}
          </span>
          <span class="stat-item" v-if="contactsStore.pendingRequestsCount > 0">
            <el-badge :value="contactsStore.pendingRequestsCount" class="badge">
              {{ $t('contacts.stats.pendingRequests') }}
            </el-badge>
          </span>
        </div>
      </div>
      
      <div class="header-actions">
        <el-button type="primary" @click="showAddFriend = true">
          <el-icon><Plus /></el-icon>
          {{ $t('contacts.actions.addFriend') }}
        </el-button>
        <el-button @click="showRequests = true">
          <el-icon><Message /></el-icon>
          {{ $t('contacts.actions.friendRequests') }}
          <el-badge v-if="contactsStore.pendingRequestsCount > 0" 
                   :value="contactsStore.pendingRequestsCount" 
                   class="ml-2" />
        </el-button>
        <el-button @click="showSettings = true">
          <el-icon><Setting /></el-icon>
          {{ $t('contacts.actions.privacySettings') }}
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          :placeholder="$t('contacts.search.placeholder')"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-tabs">
        <div class="group-selector">
          <el-radio-group v-model="selectedGroup" @change="handleGroupChange">
            <el-radio-button label="">{{ $t('contacts.groups.all') }}</el-radio-button>
            <el-radio-button
              v-for="group in contactsStore.friendGroups"
              :key="group"
              :label="group"
            >
              {{ group }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <div class="group-actions">
          <el-button
            type="primary"
            plain
            @click="showCreateGroup = true"
            :icon="Plus"
            size="small"
          >
            {{ $t('contacts.actions.createGroup') }}
          </el-button>
          <el-button
            plain
            @click="showManageGroups = true"
            size="small"
          >
            {{ $t('contacts.actions.manageGroups') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 好友列表 -->
    <div class="friends-content" v-loading="contactsStore.loading">
      <div v-if="contactsStore.friends.length === 0" class="empty-state">
        <el-empty :description="$t('contacts.empty.noFriends')">
          <el-button type="primary" @click="showAddFriend = true">
            {{ $t('contacts.empty.addFirstFriend') }}
          </el-button>
        </el-empty>
      </div>

      <div v-else class="friends-list">
        <!-- 按分组显示好友 -->
        <div 
          v-for="(friends, groupName) in contactsStore.friendsByGroup" 
          :key="groupName"
          class="friend-group"
        >
          <div class="group-header">
            <h3 class="group-title">{{ groupName }}</h3>
            <span class="group-count">({{ friends.length }})</span>
          </div>
          
          <div class="group-friends">
            <div 
              v-for="friend in friends" 
              :key="friend.relationshipId"
              class="friend-item"
              @click="handleFriendClick(friend)"
            >
              <div class="friend-avatar">
                <el-avatar
                  :src="friend.avatarUrl"
                  :size="40"
                >
                  {{ friend.realName?.charAt(0) || friend.username.charAt(0) }}
                </el-avatar>
              </div>
              
              <div class="friend-info">
                <div class="friend-name">
                  {{ friend.realName || friend.username }}
                  <el-tag v-if="friend.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
                  <el-tag v-if="friend.userType === 'ADMIN'" type="danger" size="small">管理员</el-tag>
                </div>
                <div class="friend-status">
                  <span v-if="friend.remark" class="remark">
                    {{ friend.remark }}
                  </span>
                </div>
              </div>
              
              <div class="friend-actions">
                <el-dropdown @command="handleFriendAction">
                  <el-button text>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ action: 'chat', friend }">
                        <el-icon><ChatDotRound /></el-icon>
                        发送消息
                      </el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'edit', friend }">
                        <el-icon><Edit /></el-icon>
                        编辑好友
                      </el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'delete', friend }" divided>
                        <el-icon><Delete /></el-icon>
                        删除好友
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加好友对话框 -->
    <AddFriendDialog 
      v-model="showAddFriend"
      @success="handleAddFriendSuccess"
    />

    <!-- 好友申请对话框 -->
    <FriendRequestsDialog 
      v-model="showRequests"
      @handled="handleRequestHandled"
    />

    <!-- 隐私设置对话框 -->
    <PrivacySettingsDialog 
      v-model="showSettings"
      @updated="handlePrivacyUpdated"
    />

    <!-- 编辑好友对话框 -->
    <EditFriendDialog
      v-model="showEditFriend"
      :friend="selectedFriend"
      @updated="handleFriendUpdated"
    />

    <!-- 好友详情对话框 -->
    <FriendDetailDialog
      v-model="showFriendDetail"
      :friend="selectedFriend"
      @edit="handleEditFriend"
      @delete="handleDeleteFriend"
      @chat="handleStartChat"
    />

    <!-- 创建分组对话框 -->
    <CreateGroupDialog
      v-model="showCreateGroup"
      @created="handleGroupCreated"
    />

    <!-- 管理分组对话框 -->
    <ManageGroupsDialog
      v-model="showManageGroups"
      @updated="handleGroupsUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Plus, Message, Setting, Search, MoreFilled, 
  ChatDotRound, Edit, Delete 
} from '@element-plus/icons-vue'
import { useContactsStore } from '@/stores/contacts'

// 组件导入
import AddFriendDialog from './components/AddFriendDialog.vue'
import FriendRequestsDialog from './components/FriendRequestsDialog.vue'
import PrivacySettingsDialog from './components/PrivacySettingsDialog.vue'
import EditFriendDialog from './components/EditFriendDialog.vue'
import FriendDetailDialog from './components/FriendDetailDialog.vue'
import CreateGroupDialog from './components/CreateGroupDialog.vue'
import ManageGroupsDialog from './components/ManageGroupsDialog.vue'

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const searchKeyword = ref('')
const selectedGroup = ref('')
const showAddFriend = ref(false)
const showRequests = ref(false)
const showSettings = ref(false)
const showEditFriend = ref(false)
const showFriendDetail = ref(false)
const showCreateGroup = ref(false)
const showManageGroups = ref(false)
const selectedFriend = ref(null)

// 搜索防抖
let searchTimer: NodeJS.Timeout | null = null

// 生命周期
onMounted(async () => {
  await contactsStore.initialize()
})

// 方法
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    contactsStore.getFriendsList(selectedGroup.value, searchKeyword.value)
  }, 300)
}

const handleGroupChange = () => {
  contactsStore.getFriendsList(selectedGroup.value, searchKeyword.value)
}

const handleFriendClick = (friend: any) => {
  console.log('点击好友:', friend)
  // 显示好友详情对话框
  selectedFriend.value = friend
  showFriendDetail.value = true
}

const handleEditFriend = (friend: any) => {
  selectedFriend.value = friend
  showFriendDetail.value = false
  showEditFriend.value = true
}

const handleStartChat = (friend: any) => {
  // 跳转到聊天界面
  console.log('开始聊天:', friend)
  // TODO: 实现跳转到聊天界面的逻辑
}

const handleGroupCreated = async (groupName: string) => {
  console.log('创建分组:', groupName)
  // 重新加载好友列表以确保同步（会同时更新分组信息）
  await contactsStore.getFriendsList()
}

const handleGroupsUpdated = async () => {
  console.log('分组已更新')
  // 重新加载好友列表（会同时更新分组信息）
  await contactsStore.getFriendsList()
}

const handleFriendAction = async ({ action, friend }: any) => {
  switch (action) {
    case 'chat':
      // 跳转到聊天界面
      console.log('发送消息给:', friend)
      ElMessage.info('聊天功能即将上线')
      break
      
    case 'edit':
      selectedFriend.value = friend
      showEditFriend.value = true
      break
      
    case 'delete':
      await handleDeleteFriend(friend)
      break
  }
}

const handleDeleteFriend = async (friend: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除好友 ${friend.realName || friend.username} 吗？`,
      '删除好友',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contactsStore.deleteFriend(friend.relationshipId)
  } catch (error) {
    // 用户取消删除
  }
}

const handleAddFriendSuccess = () => {
  contactsStore.getFriendsList()
}

const handleRequestHandled = () => {
  contactsStore.getFriendsList()
  contactsStore.getReceivedRequests('PENDING')
}

const handlePrivacyUpdated = () => {
  // 隐私设置更新后的处理
}

const handleFriendUpdated = () => {
  contactsStore.getFriendsList()
}


</script>

<style scoped>
.contacts-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.contacts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.stats-info {
  display: flex;
  gap: 16px;
}

.stat-item {
  font-size: 14px;
  color: var(--el-text-color-regular);
}



.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  padding: 16px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
}

.filter-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  gap: 16px;
}

.group-selector {
  flex: 1;
}

.group-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.search-bar {
  margin-bottom: 16px;
}

.friends-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 24px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.friend-group {
  margin-bottom: 24px;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.group-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.group-count {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.friend-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.friend-item:hover {
  background: var(--el-fill-color-light);
}

.friend-avatar {
  position: relative;
}



.friend-info {
  flex: 1;
  min-width: 0;
}

.friend-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.friend-status {
  font-size: 12px;
  color: var(--el-text-color-regular);
}



.remark {
  color: var(--el-text-color-placeholder);
}

.friend-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.friend-item:hover .friend-actions {
  opacity: 1;
}
</style>
